package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchResult;
import com.atguigu.gulimall.search.vo.searchParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(searchParam param) {
        SearchResult result=null;
        SearchRequest searchRequest=buildSearchRequest(param);
        try {
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            result= buildSearchResult(response,param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    private SearchResult buildSearchResult(SearchResponse response,searchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        List<SkuEsModel> skuEsModelList=new ArrayList<>();
        if (hits.getHits()!=null&& hits.getHits().length>0){
            for (SearchHit hit:hits.getHits()){
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel1 = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.fragments()[0].string();
                    skuEsModel1.setSkuTitle(string);
                }
                skuEsModelList.add(skuEsModel1);
            }
        }
        result.setProducts(skuEsModelList);
        List<SearchResult.AttrVo> attrVos=new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket:attrIdAgg.getBuckets()){
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            String attrNameAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrNameAgg);
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(bucket1 -> {
                String keyAsString = bucket1.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValue);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        List<SearchResult.BrandVO> brandVOS=new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket:brandAgg.getBuckets()) {
                SearchResult.BrandVO brandVO=new SearchResult.BrandVO();
            long branId = bucket.getKeyAsNumber().longValue();
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVO.setBrandId(branId);
            brandVO.setBrandName(brandName);
            brandVO.setBrandImg(brandImg);
            brandVOS.add(brandVO);
        }
        result.setBrands(brandVOS);
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        List<SearchResult.CatalogVO> catalogVOS=new ArrayList<>();
        for (Terms.Bucket bucket:buckets){
            SearchResult.CatalogVO catalogVO=new SearchResult.CatalogVO();
            String keyAsString = bucket.getKeyAsString();
            catalogVO.setCatalogId(Long.parseLong(keyAsString));
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVO.setCatalogName(catalogName);
            catalogVOS.add(catalogVO);
        }
        result.setCatalogs(catalogVOS);
        result.setPageNum(param.getPageNum());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        Long totalPages = total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1;
        result.setTotalPages(totalPages.intValue());
//        for (int i=1:i<=)
        if (param.getAttrs()!=null&&param.getAttrs().size()>0){
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode()==0){
                    AttrResponseVo attr1 = r.getData("attr", new TypeReference<AttrResponseVo>() {});
                    navo.setNavName(attr1.getAttrName());
                }else {
                    navo.setNavName(s[0]);
                }
                String replace = replaceQueryString(param, attr,"attrs");
                navo.setLink("http://localhost:12000/list.html?"+replace);
                return navo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        if (param.getBrandId()!=null && param.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            R r = productFeignService.brandsInfos(param.getBrandId());
            if (r.getCode()==0){
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {});
                StringBuffer stringBuffer = new StringBuffer();
                String replace="";
                for (BrandVo brandVo : brand) {
                    String brandName = brandVo.getBrandName();
                    replace = replaceQueryString(param, String.valueOf(brandVo.getBrandId()), "brandId");
                    stringBuffer.append(brandName+";");
                }
                navVo.setNavValue(stringBuffer.toString());
                navVo.setLink("http://localhost:12000/list.html?"+replace);
            }
            navs.add(navVo);
        }
        return result;
    }

    private static String replaceQueryString(searchParam param, String value,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String replace = param.get_queryString().replace("&"+key+"=" + encode, "");
        return replace;
    }

    private SearchRequest buildSearchRequest(searchParam param) {
        SearchSourceBuilder souce = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        if (param.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        if (null != param.getBrandId() && param.getBrandId().size()>0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
//        if (param.getAttrs().size()>0&&null!=param.getAttrs()){
        List<String> attrs = param.getAttrs();
//        System.out.println("attrsize"+attrs.size());
//        System.out.println("param.getAttrs().size()"+param.getAttrs().size());
        if (null != attrs && attrs.size() > 0){
            for (String attr:param.getAttrs()){
                BoolQueryBuilder nestedboolBuilder = QueryBuilders.boolQuery();
                String[] s1 = attr.split("_");
                String attrId=s1[0];
                nestedboolBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                String[] attrValues = s1[1].split(":");
                nestedboolBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolBuilder, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
//            attrs.forEach(attr->{
//                BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
//                String[] attrSplit = attr.split("_");
//                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrSplit[0]));//检索的属性的id
//                String[] attrValues = attrSplit[1].split(":");
//                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));//检索的属性的值
//                //每一个必须都得生成一个nested查询
//                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
//                boolQuery.filter(nestedQueryBuilder);
//            });
        }
        if (null!=param.getHasStock()){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
//        if (!StringUtils.isEmpty(param.getSkuPrice())){
//            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
//            String[] s = param.getSkuPrice().split("_");
//            if (s.length==2){
//                rangeQuery.gte(s[0]).lte(s[1]);
//            }else if (s.length==1){
//                if (param.getSkuPrice().startsWith("_")){
//                    rangeQuery.lte(s[0]);
//                }
//                if (param.getSkuPrice().endsWith("_")){
//                    rangeQuery.gte(s[0]);
//                }
//            }
//            boolQuery.filter(rangeQuery);
//        }
           RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String[] prices = param.getSkuPrice().split("_");
            if (prices.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(Integer.parseInt(prices[0]));
                }else {
                    rangeQuery.gte(Integer.parseInt(prices[0]));
                }
            } else if (prices.length == 2) {
                //_6000会截取成["","6000"]
                if (!prices[0].isEmpty()) {
                    rangeQuery.gte(Integer.parseInt(prices[0]));
                }
                rangeQuery.lte(Integer.parseInt(prices[1]));
            }
            boolQuery.filter(rangeQuery);
        }
        souce.query(boolQuery);
        if (!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            souce.sort(s[0],s[1].equals("asc")? SortOrder.ASC:SortOrder.DESC);
        }

        souce.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        souce.size(EsConstant.PRODUCT_PAGESIZE);
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            souce.highlighter(highlightBuilder);
        }
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(10)
                .subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1))
                .subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        souce.aggregation(brand_agg);
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20)
                .subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        souce.aggregation(catalog_agg);
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        souce.aggregation(attr_agg);
        String s = souce.toString();
        System.out.println(s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, souce);
        return searchRequest;
    }
}
